import myApi from '@/utils/app.js';
export const request = (options) => {
	console.log(options)
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('token')
		console.log(token)
		if (!options.url) {
			console.error('请传入URL')
			return;
		}
		// if (!token) {
		// 	return
		// }
		uni.request({
			url: options.url,
			data: options.data || '',
			method: options.method || 'POST',
			header: {
				"X-token": token || "",
			},
			success: (res) => {
				if (res.data.msg === "登录信息已失效，请重新登录") {
					let loginInfo = uni.getStorageSync('loginInfo');
					if (loginInfo == '') {
						uni.redirectTo({
							url: '/pages/myUser/wxSign/wxSign?fromUrl=' +
								encodeURIComponent(getCurrentPages()[
									getCurrentPages()
									.length - 1].$page.fullPath)
						})
					} else {
						wxlogin(loginInfo)
					}
				} else {
					resolve(res.data);
				}
			},
			fail: (res) => {
				resolve(res)
			}
		})
	})
};

export function login() {
	uni.login({
		desc: 'weixin',
		success: res => {
			wx.request({
				url: myApi.loginUrl,
				method: 'POST',
				data: {
					weappCode: res.code,
					weappWho: 'WX_CAR'
				},
				success: res => {
					let token = res.data.result.wxUser.rememberToken
					uni.setStorageSync('token', token);
				}
			});
		}
	});
}

export const loginTest = () => {
	return new Promise((resolve, reject) => {
		try {
			const value = uni.getStorageSync('token');
			if (value) {
				resolve('true')
			} else {
				uni.redirectTo({
					url: '/pages/myUser/wxSign/wxSign?fromUrl=' +
						encodeURIComponent(getCurrentPages()[
							getCurrentPages()
							.length - 1].$page.fullPath)
				})
			}
		} catch (e) {}
	})
}

export const preImage = (url) => {
	uni.previewImage({
		urls: [url],
		current: url
	})
}


// 全局请求封装

export const request1 = (url, method = 'get', params = {}) => {
	const token = uni.getStorageSync('token') || ''; //获取token  
	uni.showLoading({
		title: "加载中"
	});
	return new Promise((resolve, reject) => {
		uni.request({
			url: myApi.hostBaseUrl + url, // 确保myApi.hostBaseUrl已定义  
			method: method,
			header: {
				'X-Access-Token': token
			},
			data: {
				...params
			},
			success(res) {
				console.log('request', res.data);
				if (res.data.status == 500) {
					let loginInfo = uni.getStorageSync('loginInfo');
					uni.showModal({
						title: '提示',
						content: res.data.message, // 使用res.data.msg代替parsedObj.data.msg  
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								// 处理重定向的异步操作
								uni.redirectTo({
									url: '/pages/loginPage/index'
								})
							}
						}
					});
				} else {
					if (res.data.code != 200) {
						uni.showModal({
							title: '提示',
							content: res.data.msg, // 使用res.data.msg代替parsedObj.data.msg  
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								}
							}
						});
						return;
					}
					resolve(res);
				}
			},
			fail(err) {
				// 对错误进行更详细的处理或给用户更具体的反馈  
				reject(err);
			},
			complete() {
				setTimeout(() => {
					uni.hideLoading();
				}, 1000);
			}
		});
	});
};



function wxlogin(msg) {
	let that = this;
	uni.showLoading({
		title: '登录中'
	});
	uni.login({
		desc: 'weixin',
		success: loginRes => {
			wx.getUserInfo({
				success: function(res) {
					uni.request({
						url: myApi.loginUrl,
						data: {
							code: loginRes.code,
							rawData: res.rawData,
							signature: res.signature,
							userInfo: msg
						},
						method: 'GET',
						success(res) {
							console.log('登陆成功')
							console.log(res)
							let userInfo = res.data.data //登陆返回的所有数据
							uni.setStorageSync('userInfo', userInfo) //保存全部数据
							uni.setStorageSync('dadaes', userInfo) //保存全部数据
							uni.setStorageSync('token', userInfo
								.token) //保存code'

							var pages = getCurrentPages(); //获取所有页面的数组对象
							var currPage = pages[pages.length - 1]; //当前页面
							uni.reLaunch({
								url: currPage.$page.fullPath
							})
						},
						fail() {
							that.$refs.uNotify.show({
								message: '授权失败，请联系管理员',
								type: 'error'
							});
						}
					});
				}
			})
		}
	});
};

function uploadFilePromise(filePath) {
	return new Promise((resolve, reject) => {
		const api = 'http://192.168.1.16:8080/jeecg-boot/sys/common/upload';
		uni.uploadFile({
			url: api,
			name: 'file',
			filePath: filePath,
			formData: {
				'biz': "scott/pic",
				'file': "（二进制）"
			},
			success: (res) => {
				console.log(res);
				if (res.statusCode === 200) {
					// 解析服务器返回的数据，如果有需要的话  
					// 例如：const data = JSON.parse(res.data);  
					resolve(data); // 假设服务器返回了有效数据  
				} else {
					const obj = {
						message: '上传失败',
						type: 'error',
						statusCode: res.statusCode
					};
					reject(obj); // 返回一个错误对象  
				}
			},
			fail: (error) => {
				console.log(`文件请求失败`, error);
				const obj = {
					message: '上传请求失败',
					type: 'error',
					errorDetails: error
				};
				reject(obj); // 返回一个错误对象  
			}
		});
	});
};

/**
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
	const date = new Date(time / 1)
	const y = date.getFullYear()
	let m = date.getMonth() + 1
	m = m < 10 ? '' + m : m
	let d = date.getDate()
	d = d < 10 ? '' + d : d
	let h = date.getHours()
	h = h < 10 ? '0' + h : h
	let minute = date.getMinutes()
	let second = date.getSeconds()
	minute = minute < 10 ? '0' + minute : minute
	second = second < 10 ? '0' + second : second
	return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
};